package com.github.livebase.util.base;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName IOUtil
 * @description:
 * @author: biao532
 * @create: 2023-12-08 18:31
 * @Version 1.0
 **/
public class IOUtil {
    static final char[] digits = {
            '0' , '1' , '2' , '3' , '4' ,
            '5' , '6' , '7' , '8' , '9' ,
            'a' , 'b' , 'c' , 'd' , 'e' , 'f'
    };
    public static String toString(InputStream inputStream) throws IOException {
        if (null == inputStream) {
            return null;
        }
        try(ByteArrayOutputStream stream = new ByteArrayOutputStream(inputStream.available())) {
            transferTo(inputStream, stream);
            byte[] bs = stream.toByteArray();
            return new String(bs, 0, bs.length, StandardCharsets.UTF_8);
        }
    }
    public static void consume(InputStream inputStream) throws IOException {
        byte[] bs = new byte[1024];
        while (-1 != inputStream.read(bs)) {

        }
    }
    public static ByteArray transferToByteArray(InputStream inputStream, int size) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        long s = transferTo(inputStream, stream, size < 0 ? Integer.MAX_VALUE : size);
        ByteArray array = new ByteArray(stream.toByteArray());
        stream.close();
        return array;
    }
    public static long transferTo(InputStream inputStream, OutputStream outputStream, long size) throws IOException {
        byte[] bs = new byte[1024];
        long all = 0;
        int len = -1;
        while (size > 0 && -1 != (len = inputStream.read(bs, 0, size > 1024? 1024 : (int) size))) {
            outputStream.write(bs, 0, len);
            all += len;
        }
        return all;
    }
    public static long transferTo(InputStream inputStream, OutputStream outputStream) throws IOException {
        return transferTo(inputStream, outputStream, Long.MAX_VALUE);
    }
    public static String toHex(byte... bs) {
        StringBuilder builder = new StringBuilder(bs.length*2);
        for (byte b : bs) {
            builder.append(digits[(b >> 4) & 0xf]);
            builder.append(digits[b & 0x0f]);
        }
        return builder.toString();
    }
}
